package com.ming.stringstudy.feedbacksystem.Aop;

import com.ming.stringstudy.feedbacksystem.Exception.PermissionDeniedException;
import com.ming.stringstudy.feedbacksystem.anno.PermissionLog;
import com.ming.stringstudy.feedbacksystem.utils.HeaderName;
import com.ming.stringstudy.feedbacksystem.utils.JwtUtils;
import com.ming.stringstudy.feedbacksystem.utils.PermissionUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 权限管理Aspect
 */

@Slf4j
@Component
@Aspect
public class PermissionAspect {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private PermissionUtils permissionUtils;
    /**
     * 权限通知
     */
    @Around("@annotation(com.ming.stringstudy.feedbacksystem.anno.PermissionLog) && " +
            "@annotation(permissionLog)" //获取注解上的参数
            )
    public Object permissionAdvice(ProceedingJoinPoint joinPoint,PermissionLog permissionLog) throws Throwable {
        log.info("当前接口需要权限{}",permissionLog.value());

        Integer roleId = JwtUtils.parserJwt(request.getHeader(HeaderName.headerName)).get("roleId",Integer.class);
        if(!permissionUtils.equalPermission(roleId,permissionLog.value())){
            log.info("权限不足，无法调用{}方法",joinPoint.getSignature().getName());
            throw new PermissionDeniedException("权限不足");
        }
        return joinPoint.proceed();
    }
}
